package eu.webhib.webblog.domain.base;

import eu.webhib.extgui.data.intf.DataItem;
import eu.webhib.frmwrk.persistence.PersistenceMngr;
import eu.webhib.webblog.domain.base.intf.CommonBaseEntity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
import org.apache.log4j.Logger;

/**
 * Application common base type of entities
 * see http://stackoverflow.com/questions/156689/do-you-have-a-common-base-class-for-hibernate-entities
 * see http://community.jboss.org/wiki/EqualsandHashCode
 */
@MappedSuperclass()
@Access(AccessType.FIELD)
public abstract class CommonBaseEntityImpl implements
        Serializable, CommonBaseEntity {

   private static final Logger log = Logger.getLogger(CommonBaseEntityImpl.class);
   @Version
   private Long version;
   @Temporal(TemporalType.TIMESTAMP)
   @Column(nullable = false)
   private Date creationTime;
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   protected Long id;

   public CommonBaseEntityImpl() {
      creationTime = new Date();
   }

   public Long getVersion() {
      return version;
   }

   public Date getCreationTime() {
      return creationTime;
   }

   /**
    * @see DataItem interface
    * @param other other item to compare
    * @return Whether this item is identical to another CommonBaseEntityImpl
    */
   @Override
   public boolean identical(DataItem other) {
      assert (other != null);
      if (!PersistenceMngr.identicalClass(this, other)) {
         //log.trace("identical - class mismatch: " + this.getClass().getSimpleName() + " " + other.getClass().getSimpleName());
         return false;
      }
      boolean ret = this.getId().equals(((CommonBaseEntityImpl) other).getId());
      //log.trace("identical - rc: " + ret + (ret ? "" : " " + this.getId() + " " + ((CommonBaseEntityImpl) other).getId()));
      return (ret);
   }

   /**
    * Just for logging
    */
   @Override
   public String toString() {
      return new StringBuilder(getClass().getSimpleName()).append(":").append(getId()).toString();
   }

   @Override
   public Long getId() {
      return id;
   }

   @Override
   public void setId(Long id) {
      this.id = id;
   }
   /**
    * we do not overwrite hashcode() or equals() as we do not use the entities as composite-id nor
    * do we use a collection after saving
    */
}
